package com.zrrd.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zrrd.article.service.ApArticleService;
import com.zrrd.article.service.ArticleFreemarkerService;
import com.zrrd.file.service.FileStorageService;
import com.zrrd.model.article.pojos.ApArticle;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author WanJl
 * @version 1.0
 * @title ArticleFreemarkerServiceImpl
 * @description
 * @create 2023/9/26 16:06
 */
@Service
@Slf4j
@Transactional
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {

    @Autowired
    private Configuration configuration;

    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    ApArticleService apArticleService;
    /**
     * 生成静态文件并且上传到MinIO中
     *
     * @param article
     * @param content
     */
    @Override
    public void buidArticleToMinIO(ApArticle article, String content) {
        //1、获取新闻内容
        if (StringUtils.isNotBlank(content)){
            StringWriter out = new StringWriter();
            Template template=null;
            //2、新闻内容通过freemarker生成html文件
            try {
                template = configuration.getTemplate("article.ftl");
                //生成数据模型
                Map<String, Object> params = new HashMap<>();
                params.put("content", JSONArray.parseArray(content));
                //合成
                template.process(params, out);
            } catch (Exception e) {
                e.printStackTrace();
            }
            //3、把html文件上传到MinIO中
            InputStream is = new ByteArrayInputStream(out.toString().getBytes());
            String path = fileStorageService.uploadHtmlFile("",article.getId() + ".html", is);

            //4、修改ap_article表，保存static_url字段
            apArticleService.update(Wrappers.<ApArticle>lambdaUpdate()
                    .eq(ApArticle::getId,article.getId())
                    .set(ApArticle::getStaticUrl,path));
        }

    }
}
